<template>
  <div class="m-upload-single">
		<label class="upItem" v-if="type=='idcard'">
			<div class="IdpicBox" v-if="!defaltPic">
				<img src="~/assets/images/addPic.png" class="icon"/>
				<div class="f16 cor666 txt">{{msg}}</div>
			</div>
			<div class="IdpicBox" v-else>
				<img :src="defaltPic" class="objectCover"/>
			</div>
			<input type="file" name="filed" class="upInput" @change="upLoad"/>
		</label>
		<label class="upItem" v-else>
			<div class="btn transition">上传/更改</div>
			<input type="file" name="filed" class="upInput" @change="upLoad"/>
		</label>
	</div>
</template>

<script>
import { uploadPic } from '@/request/api'
export default {
  name: 'MUploadSingle',
  props: {
    type:String,
		msg:String,
		defaltPic:String
  },
  data() {
    return {
    }
  },
	created(){
		this.pic = this.defaltPic || ''
	},
  methods: {
		upLoad(e){
			var file = e.target.files[0]
			let that = this
			if(that.beforeUpload(file)){
				var imgSrc  = file
				let fordata = new FormData()
				fordata.append("field", imgSrc)
				if (/^image/.test(imgSrc.type)) {
					that.$toastVant.loading('上传中')
					uploadPic(fordata).then(res => {
						that.$emit('getPic',res.data.path)
						setTimeout(function(){
							that.$toastVant.clear()
						},1000)
					  }
					)
				} else {
					that.$toastVant('只能上传.png,.jpg,jpeg的图片')
				}
			}
		},
		beforeUpload(file){
		  var that=this
			//文件类型
			var fileName=file.name.substring(file.name.lastIndexOf('.')+1)
			if(fileName!='png' && fileName!='jpg' && fileName!='jpeg'){
				that.uploadTemplateDialog=false
				that.$toastVant('只能上传.png,.jpg,jpeg的图片')
				return false
			}
			//读取文件大小
			var fileSize=file.size
			if(fileSize>1024*1024){
				that.uploadTemplateDialog=false
				that.$toastVant('文件大于1M')
				return false
			}else{
				return true
			}
		}
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/style/common.scss";
.m-upload-single{
	.upItem{
		display: block;
		font-weight: normal;
		position: relative;
		.IdpicBox{
			border: dashed 2px #969696;
			border-radius: 10px;
			display: flex;
			flex-wrap: wrap;
			justify-content: center;
			align-content: center;
			position: relative;
			height: 200px;
			cursor: pointer;
			overflow: hidden;
			.icon{
				width: 64px;
				height: 64px;
			}
			.txt{
				width: 100%;
				margin-top: 10px;
				text-align: center;
			}
		}
		.picBox{
			background-color: #fbfdff;
			border: 1px dashed #c0ccda;
			border-radius: 6px;
			box-sizing: border-box;
			width: 148px;
			height: 148px;
			line-height: 146px;
			vertical-align: top;
		}
		.btn{
			width: 120px;
			height: 40px;
			border: 1px solid $theme-color-1;
			display: flex;
			justify-content: center;
			align-items: center;
			color: $theme-color-1;
			cursor: pointer;
			border-radius: 20px;
			&:hover{
				background: $theme-color-1;
				color:#fff;
			}
		}
		.upInput{
			position: absolute;
			// opacity: 0;
			top: 0;
			left: 0;
			visibility: hidden;
		}
	}
	
}
</style>
